package com.huizhonglm.diap.ui.user;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bruce.crop.Crop;
import com.bruce.common.utils.EmptyUtil;
import com.bruce.common.utils.FileUtil;
import com.bruce.common.utils.PictureUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.API;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.image.Thumb;
import com.huizhonglm.diap.core.storage.model.UserInfo;
import com.huizhonglm.diap.core.storage.model.district.CityInfo;
import com.huizhonglm.diap.core.storage.model.district.DistInfo;
import com.huizhonglm.diap.core.storage.model.district.ProvInfo;
import com.huizhonglm.diap.core.utils.DialogUtil;
import com.huizhonglm.diap.core.utils.LogUtil;
import com.huizhonglm.diap.core.utils.SdcardUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.core.zxing.QRcodeUtils;
import com.huizhonglm.diap.presenters.user.UserInfoPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.iView.UserInfoIView;
import com.huizhonglm.diap.ui.views.CityPickerView;
import com.huizhonglm.diap.ui.views.ImageChooseView;
import com.huizhonglm.diap.widget.RoundImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-03 10:53
 */
public class UserInfoActivity extends BaseActivity implements UserInfoIView, View.OnClickListener,
        CityPickerView.OnDistrictSetListener, ImageChooseView.OnImageChooseListener {
    private final int GALLERY_REQ_CODE = 0;
    private final int CAMERA_REQ_CODE = 1;

    private CityPickerView cityPickView;
    private ImageChooseView imgChooseView;

    private TextView nameTxt;
    private TextView nicknameTxt;
    private TextView locationTxt;
    private TextView addressTxt;
    private TextView sexTxt;
    private RoundImageView userIconImg;
    private ImageView my_rcode_ibtn;

    private UserInfoPresenter mPresenter;

    private String defSex = "M";

    private String provID;
    private String cityID;
    private String distID;
    private String provName;
    private String cityName;
    private String distName;

    private String cameraName = "camera.jpg";
    private String filePath;
    private String imgPath;
    private Bitmap photo;

    private UserInfo user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        setBackEvent(this, null);
        mPresenter = new UserInfoPresenter(this);
        user = UserUtil.getUserInfo();
        assignViews();
    }

    @Override
    protected void assignViews() {
        filePath = SdcardUtil.getTempPath() + "userIcon/";
        FileUtil.createDir(filePath);
        imgPath = filePath + Constants.USER_ICON;
        FileUtil.delete(new File(imgPath));

        nameTxt = (TextView) findViewById(R.id.name_txt);
        nicknameTxt = (TextView) findViewById(R.id.nickname_txt);
        locationTxt = (TextView) findViewById(R.id.location_txt);
        addressTxt = (TextView) findViewById(R.id.detail_addr_txt);
        sexTxt = (TextView) findViewById(R.id.sex_txt);
        userIconImg = (RoundImageView) findViewById(R.id.user_icon_rimg);
        my_rcode_ibtn = (ImageView) findViewById(R.id.my_rcode_ibtn);
        View iconLayout = findViewById(R.id.user_icon_layout);

        cityPickView = new CityPickerView(this, findViewById(R.id.user_info_page), this);
        imgChooseView = new ImageChooseView(this, findViewById(R.id.user_info_page), this);

        nameTxt.setOnClickListener(this);
        nicknameTxt.setOnClickListener(this);
        locationTxt.setOnClickListener(this);
        addressTxt.setOnClickListener(this);
        sexTxt.setOnClickListener(this);
        my_rcode_ibtn.setOnClickListener(this);
        iconLayout.setOnClickListener(this);

        setInfoValue();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.name_txt:
                showInputDialog(Constants.MODIFY_NAME, "姓名", "请输入姓名", nameTxt.getText().toString());
                break;
            case R.id.nickname_txt:
                showInputDialog(Constants.MODIFY_NICKNAME, "昵称", "请输入昵称", nicknameTxt.getText().toString());
                break;
            case R.id.location_txt:
                closeKeyboard(UserInfoActivity.this);
                cityPickView.show(provName, cityName, distName);
                break;
            case R.id.detail_addr_txt:
                showInputDialog(Constants.MODIFY_ADDRESS, "地址", "请输入地址", addressTxt.getText().toString());
                break;
            case R.id.sex_txt:
                showSexDialog();
                break;
            case R.id.user_icon_layout:
                imgChooseView.show();
                break;
            case R.id.my_rcode_ibtn:
                if (v.getTag()!=null){
                    DialogUtil.showTwoCodeDialog(UserInfoActivity.this, v.getTag().toString());
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onModifySuccess(String flag, String newValue) {
        hideProgressBar();
        switch (flag) {
            case Constants.MODIFY_NAME:
                user.setUserName(newValue);
                ToastUtil.makeTextShort("名称修改成功");
                break;
            case Constants.MODIFY_NICKNAME:
                user.setNickName(newValue);
                ToastUtil.makeTextShort("昵称修改成功");
                break;
            case Constants.MODIFY_SEX:
                defSex = newValue;
                user.setUserSex(newValue);
                ToastUtil.makeTextShort("性别修改成功");
                break;
            case Constants.MODIFY_DISTRICT:
                user.setProvinceId(provID);
                user.setProvinceName(provName);
                user.setCityId(cityID);
                user.setCityName(cityName);
                user.setDistrictId(distID);
                user.setDistrictName(distName);
                ToastUtil.makeTextShort("地区修改成功");
                break;
            case Constants.MODIFY_ADDRESS:
                user.setAddress(newValue);
                ToastUtil.makeTextShort("地址修改成功");
                break;
        }
        UserUtil.saveUserInfo(user);
        setInfoValue();
    }

    @Override
    public void onModifyFailure(String flag) {
        hideProgressBar();
        switch (flag) {
            case Constants.MODIFY_NAME:
                ToastUtil.makeTextShort("名称修改失败，请稍后重试");
                break;
            case Constants.MODIFY_NICKNAME:
                ToastUtil.makeTextShort("昵称修改失败，请稍后重试");
                break;
            case Constants.MODIFY_SEX:
                ToastUtil.makeTextShort("性别修改失败，请稍后重试");
                break;
            case Constants.MODIFY_DISTRICT:
                ToastUtil.makeTextShort("地区修改失败，请稍后重试");
                break;
            case Constants.MODIFY_ADDRESS:
                ToastUtil.makeTextShort("地址修改失败，请稍后重试");
                break;
        }
    }

    @Override
    public void onUploadSuccess(String newIcon) {
        hideProgressBar();
        ToastUtil.makeTextShort("头像上传成功");
        user.setUserIcon(newIcon);
        UserUtil.saveUserInfo(user);
        setInfoValue();
    }

    @Override
    public void onUploadFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("头像上传失败，请稍后重试");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GALLERY_REQ_CODE:
                    if (data != null) {
                        String dataPath = getImagePath(data.getData());
                        String zoomPath = filePath + System.currentTimeMillis() + "-album.jpg";
                        String picPath = PictureUtil.ZoomPicture(dataPath, zoomPath);
                        zoomImage(Uri.fromFile(new File(picPath)));
                    }
                    break;
                case CAMERA_REQ_CODE:
                    if (FileUtil.isSdcardMounted()) {
                        String zoomPath = filePath + System.currentTimeMillis() + "-camera.jpg";
                        String picPath = PictureUtil.ZoomPicture(filePath + cameraName, zoomPath);
                        zoomImage(Uri.fromFile(new File(picPath)));
                    } else {
                        ToastUtil.makeTextShort("无SD卡");
                    }
                    break;
                case Crop.REQUEST_CROP:
                    if (data != null) {
                        setZoomImgToView();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDistrictSet(ProvInfo prov, CityInfo city, DistInfo dist) {
        if (!provID.equals(prov.getProvId()) || !cityID.equals(city.getCityCode()) || !distID.equals(dist.getDistId())) {
            provName = prov.getProvName();
            cityName = city.getCityName();
            distName = dist.getDistName();
            provID = prov.getProvId();
            cityID = city.getCityCode();
            distID = dist.getDistId();
            locationTxt.setText(getLocation(provName, cityName, distName));
            showProgressBar();
            mPresenter.modifyInfo(Constants.MODIFY_DISTRICT, provID, cityID, distID);
        }
    }

    @Override
    public void onGallery() {
        if (FileUtil.isSdcardMounted()) {
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Intent intentFromGallery = new Intent(Intent.ACTION_PICK, uri);
            startActivityForResult(intentFromGallery, GALLERY_REQ_CODE);
        } else {
            ToastUtil.makeTextShort("无SD卡");
        }
    }

    @Override
    public void onCamera() {
        // 判断存储卡是否可以用，可用进行存储
        if (FileUtil.isSdcardMounted()) {
            File file = new File(filePath, cameraName);
            if (file.exists()) {
                file.delete();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(filePath + cameraName)));
            startActivityForResult(intent, CAMERA_REQ_CODE);
        } else {
            ToastUtil.makeTextShort("无SD卡");
        }
    }

    private void setInfoValue() {
        if (user != null) {
            LogUtil.print("DIAP_API", "setInfoValue - user=" + JSON.toJSONString(user));
            Thumb.getInstance().display(userIconImg, user.getUserIcon(), R.drawable.def_icon);
            Thumb.getInstance().display(my_rcode_ibtn, user.getTwodCodeImg(), R.drawable.ic_rcode);
            my_rcode_ibtn.setTag(user.getTwodCodeImg());

            if (user.getUserName() != null) {
                nameTxt.setText(user.getUserName());
            }

            if (user.getNickName() != null) {
                nicknameTxt.setText(user.getNickName());
            }
            if (user.getUserSex() != null) {
                defSex = user.getUserSex();
                switch (defSex) {
                    case "M":
                        sexTxt.setText("男");
                        break;
                    case "F":
                        sexTxt.setText("女");
                        break;
                }
            }
            if (user.getProvinceName() != null && user.getCityName() != null && user.getDistrictName() != null) {
                provName = user.getProvinceName();
                cityName = user.getCityName();
                distName = user.getDistrictName();
                provID = user.getProvinceId();
                cityID = user.getCityId();
                distID = user.getDistrictId();
                locationTxt.setText(getLocation(provName, cityName, distName));
            }else{
                provName = "";
                cityName =  "";
                distName =  "";
                provID =  "";
                cityID =  "";
                distID = "";
                locationTxt.setText(getLocation(provName, cityName, distName));
            }
            addressTxt.setText(user.getAddress());
        }
    }

    private String getLocation(String pName, String cName, String dName) {
        StringBuilder builder = new StringBuilder();
        switch (pName) {
            case "北京":
            case "上海":
            case "天津":
            case "重庆":
                builder.append(cName);
                break;
            case "台湾":
            case "香港":
            case "澳门":
                builder.append(pName).append("  ").append(cName);
                break;
            default:
                builder.append(pName).append("省").append("  ").append(cName);
                break;
        }
        builder.append("  ").append(dName);
        return builder.toString();
    }

    private void showInputDialog(final String flag, String title, String hint, String def) {
        DialogUtil.showInputDialog(this, title, hint, def, new DialogUtil.OnDialogBtnClickListener() {
            @Override
            public void onBtnClick(String btnText) {
                boolean canModify = false;
                switch (flag) {
                    case Constants.MODIFY_NAME:
                        if (!nameTxt.getText().equals(btnText)) {
                            canModify = true;
                        }
                        break;
                    case Constants.MODIFY_NICKNAME:
                        if (!nicknameTxt.getText().equals(btnText)) {
                            canModify = true;
                        }
                        break;
                    case Constants.MODIFY_ADDRESS:
                        if (!addressTxt.getText().equals(btnText)) {
                            canModify = true;
                        }
                        break;
                }
                if (canModify) {
                    showProgressBar();
                    mPresenter.modifyInfo(flag, btnText);
                }
            }
        });
    }

    private void showSexDialog() {
        DialogUtil.showSexDialog(this, defSex, new DialogUtil.OnSexCheckedChangedListener() {
            @Override
            public void onSexCheckedChanged(String sex) {
                if (EmptyUtil.isEmpty(sex)) {
                    return;
                }
                if (!defSex.equals(sex)) {
                    showProgressBar();
                    mPresenter.modifyInfo(Constants.MODIFY_SEX, sex);
                }
            }
        });
    }

    public void zoomImage(Uri source) {
        new Crop(source).output(getZoomUri()).asSquare().withMaxSize(300, 300).start(UserInfoActivity.this);
    }

    public void setZoomImgToView() {
        if (getZoomUri() != null) {
            try {
                InputStream is = getContentResolver().openInputStream(getZoomUri());
                photo = BitmapFactory.decodeStream(is);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (photo != null) {
                userIconImg.setImageBitmap(photo);
            }
            showProgressBar();
            mPresenter.uploadIcon(imgPath);
        }
    }

    public String getImagePath(Uri uri) throws IllegalArgumentException {
        String path = null;
        if (uri != null) {
            String uriStr = uri.toString();
            if (uriStr.contains("file:///")) {
                path = uri.getPath();
            } else {
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
                if (cursor != null) {
                    int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    path = cursor.getString(index);
                }
            }
        }
        if (path != null) {
            if (path.contains("http") || path.contains("HTTP") || path.contains("https")
                    || path.contains("HTTPS") || path.contains("ftp") || path.contains("FTP")) {
                path = null;
                ToastUtil.makeTextShort("图片加载失败");
            }
        } else {
            ToastUtil.makeTextShort("图片加载失败");
        }
        return path;
    }

    private Uri getZoomUri() {
        try {
            File file = null;
            if (FileUtil.isSdcardMounted()) {
                file = new File(imgPath);
                if (!file.exists()) {
                    file.createNewFile();
                }
            }
            if (file == null) {
                return null;
            } else {
                return Uri.fromFile(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
